package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResBase;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResCard;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResReCards;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResState;
import com.oracle.zebrafreelytraveling.data.bean.Replay;
import com.oracle.zebrafreelytraveling.data.bean.User;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.HeaderAndFooterWrapper;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.LoadMoreWrapper;
import com.oracle.zebrafreelytraveling.utils.StringUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ConvertUtils;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;
import com.oracle.zebrafreelytraveling.utils.GsonUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/8/3.
 * 帖子详页
 */

public class CardInfoActivity extends BaseActitvity implements View.OnClickListener {

    private static final String CARD = "card";
    //传过来的帖子数据
    private ResCard.DataBean cardInfo;

    private SimpleDraweeView mCardHeadImg;
    private TextView mCardName;
    private Button mCardFan;
    private TextView mCardContent;
    private TagFlowLayout mCardLabelLayout;
    private ImageButton mCardReceiveBtn;
    private TextView mCardReceiveInfo;
    private TextView mCardTime;
    private EditText mCardRecard;
    private Button mRecardBtn;
    private RecyclerView mCardImageRecycle;

    private RecyclerView mReCardRecycleview;
    private CommonAdapter<ResReCards.DataBean> mReCardRecycleAdapter;
    private LoadMoreWrapper mLoadMoreWrapper;
    private HeaderAndFooterWrapper mHFWrapper;
    private View mHFView;
    private List<ResReCards.DataBean> mResCardList;
    private ViewHolder mResCardHolder;

    private SimpleDraweeView mReCardUserHeadImg;

    private Disposable mDisposable;

    private int page = 0;
    private boolean isListNull = false;
    private Context mContext;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        getIntentData();
        initView();
        initDisplay();
        initRecycle();
        initReCardList();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_card_info;
    }

    private void initView() {

        mHFView = LayoutInflater.from(this).inflate(R.layout.head_item_card_info, null);
        mCardHeadImg = (SimpleDraweeView) mHFView.findViewById(R.id.card_head_img);
        mCardName = (TextView) mHFView.findViewById(R.id.card_name);
        mCardFan = (Button) mHFView.findViewById(R.id.card_fan);
        mCardContent = (TextView) mHFView.findViewById(R.id.card_content);
        mCardImageRecycle= (RecyclerView) mHFView.findViewById(R.id.card_image_recycle);
        mCardLabelLayout = (TagFlowLayout) mHFView.findViewById(R.id.card_label);
        mCardReceiveBtn = (ImageButton) mHFView.findViewById(R.id.card_receive_btn);
        mCardReceiveInfo = (TextView) mHFView.findViewById(R.id.card_receive_info);
        mCardTime = (TextView) mHFView.findViewById(R.id.card_time);
        mCardRecard = (EditText) findViewById(R.id.card_recard);
        mRecardBtn = (Button) findViewById(R.id.recard_btn);
        mReCardRecycleview = (RecyclerView) findViewById(R.id.recard_list);

        mRecardBtn.setOnClickListener(this);
        mCardFan.setOnClickListener(this);
        mCardReceiveBtn.setOnClickListener(this);
    }

    private void initRecycle(){
        String imageUri = cardInfo.getCard().getImg();
        List<String> imgList = StringUtil.formatImgList(imageUri);
        if (imgList == null) {
            return;
        }
        if (imgList.size() > 9){
            for (int i = 9; i < imgList.size(); i++) {
                imgList.remove(i);
            }
        }
        if (imgList.size() == 1){
            mCardImageRecycle.setLayoutManager(new LinearLayoutManager(mContext));
        } else if (imgList.size() % 2 == 0){
            mCardImageRecycle.setLayoutManager(new GridLayoutManager(mContext, 2));
        } else if (imgList.size() % 2 != 0 && imgList.size() != 1){
            mCardImageRecycle.setLayoutManager(new GridLayoutManager(mContext, 3));
        }
        mCardImageRecycle.setAdapter(new CommonAdapter<String>(mContext, R.layout.item_card_img, imgList) {
            @Override
            protected void convert(ViewHolder holder, String s, int position) {
                SimpleDraweeView image = holder.getView(R.id.card_list_image);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                params.height = ConvertUtils.dp2px(90);
                params.topMargin = ConvertUtils.dp2px(10);
                params.bottomMargin = ConvertUtils.dp2px(10);
                params.leftMargin = ConvertUtils.dp2px(5);
                params.rightMargin = ConvertUtils.dp2px(5);
                image.setLayoutParams(params);
                image.setImageURI(Constant.DOWNLOAD_URL + s);
            }
        });
    }

    private void initReCardList() {
        mReCardRecycleview.setLayoutManager(new LinearLayoutManager(this));
        mResCardList = new ArrayList<>();
        mReCardRecycleAdapter = new CommonAdapter<ResReCards.DataBean>(this, R.layout.item_card_info_recard, mResCardList) {
            @Override
            protected void convert(ViewHolder holder, ResReCards.DataBean dataBean, int position) {
                holder.setText(R.id.recard_user_name, dataBean.getUserName());
                mReCardUserHeadImg = holder.getView(R.id.recard_user_head);
                mReCardUserHeadImg.setImageURI(dataBean.getHeadImg());
                holder.setText(R.id.recard_user_content, dataBean.getReCard().getText());
                holder.setText(R.id.recard_user_time, ConvertUtils.getNormalTimeFormat(dataBean.getReCard().getTime()));
            }
        };
        mLoadMoreWrapper = new LoadMoreWrapper(mReCardRecycleAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.footer_loading);
        mLoadMoreWrapper.setOnLoadMoreListener(viewHolder -> {
            mResCardHolder = viewHolder;
            //上拉加载获取帖子
            if (!isListNull) {
                getResCards(cardInfo.getCard().getCardid());
            } else {
                viewHolder.getConvertView().setVisibility(View.GONE);
            }

        });
        mHFWrapper = new HeaderAndFooterWrapper(mLoadMoreWrapper);
        mHFWrapper.addHeaderView(mHFView);
        //初始化跟更新获取帖子
        mReCardRecycleview.setAdapter(mHFWrapper);
        getResCards(cardInfo.getCard().getCardid());

    }

    /**
     * 获取的帖子显示
     */
    private void initDisplay() {
        mCardHeadImg.setImageURI(cardInfo.getHeadImg());
        mCardName.setText(cardInfo.getUserName());
        mCardContent.setText(cardInfo.getCard().getContent());
        String[] cardLabelList = StringUtil.formatLabelList(cardInfo.getCard().getLabel());
        if (cardLabelList != null){
            mCardLabelLayout.setAdapter(new TagAdapter<String>(cardLabelList) {
                @Override
                public View getView(FlowLayout parent, int position, String o) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tag_card_label_tv,
                            mCardLabelLayout, false);
                    tv.setText(o);
                    return tv;
                }
            });
        }
        mCardReceiveInfo.setText(cardInfo.getCard().getReceive()+"");
        String time = cardInfo.getCard().getTime();
        mCardTime.setText(ConvertUtils.getNormalTimeFormat(time));
    }

    private void addReCard() {
        String content = mCardRecard.getText().toString();
        if (content.length() < 0) {
            ToastUtil.showToast(getString(R.string.content_null));
            return;
        }

        if (!UserUtil.isLogin()){
            return;
        }
        User user = UserUtil.getUserInfoFromSP();
        Replay replay = new Replay();
        replay.setReplyId(cardInfo.getCard().getCardid());
        replay.setImg("");
        replay.setText(content);
        replay.setUserId(user.getUserId());
        replay.setTime(System.currentTimeMillis() + "");
        replay.setType(0);
        replay.setReceive(0);
        String repalyJson = GsonUtil.getInstance().toJson(replay);
        uploadReCard(repalyJson);
    }

    private void uploadReCard(String recard) {
        HttpManager.getInstance()
                .getService(Constant.BASE_URL)
                .addReCards(recard)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResBase<Replay>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResBase<Replay> resBase) {
                        if (resBase.getCode().equals(Constant.REQUEST_SUCCESS)) {
                            User user = UserUtil.getUserInfoFromSP();
                            ResReCards.DataBean bean = new ResReCards.DataBean();
                            bean.setHeadImg(user.getHeadImg());
                            bean.setUserName(user.getName());
                            bean.setReCard(resBase.getData());
                            mResCardList.add(bean);
                            mCardRecard.setText("");
                        }
                        ToastUtil.showToast(resBase.getMessage());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("recarderror", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        mHFWrapper.notifyDataSetChanged();
                        mReCardRecycleview.smoothScrollToPosition(mResCardList.size());
                    }
                });
        page++;
    }

    private void getResCards(int cardId) {
        HttpManager.getInstance()
                .getService(Constant.BASE_URL)
                .getReCardFromCard(cardId, page, Constant.MAX_PAGE)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResReCards>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResReCards resReCards) {
                        if (resReCards.getCode().equals(Constant.REQUEST_SUCCESS)) {
                            mResCardList.addAll(resReCards.getData());
                            isListNull = false;
                        } else {
                            isListNull = true;
                        }
                        ToastUtil.showToast(resReCards.getMessage());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("CardInfoActvity", e.getMessage());
                        mResCardHolder.getConvertView().setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {
                        mHFWrapper.notifyDataSetChanged();
                        if (mResCardHolder != null) {
                            mResCardHolder.getConvertView().setVisibility(View.GONE);
                        }
                    }
                });
        page++;
    }

    private void getIntentData() {
        Intent intent = getIntent();
        cardInfo = (ResCard.DataBean) intent.getSerializableExtra(CARD);

    }

    /**
     * 关注贴主
     */
    private void concernUser() {
        if (!UserUtil.isLogin()){
            return;
        }
        User user = UserUtil.getUserInfoFromSP();
        HttpManager.getInstance().getService(Constant.BASE_URL)
                .concernUser(user.getUserId(), cardInfo.getCard().getUserId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResState>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResState resState) {
                        ToastUtil.showToast(resState.getMessage());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("concernUser", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public static void startCardInfoActivity(Activity activity, ResCard.DataBean card) {
        Intent intent = new Intent(activity, CardInfoActivity.class);
        intent.putExtra(CARD, card);
        activity.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.card_fan:
                //TODO 关注
                concernUser();
                break;
            case R.id.card_receive:
                //TODO 点赞
                break;
            case R.id.recard_btn:
                //TODO 回帖按钮
                addReCard();
                break;
        }
    }
}
